package Syn;

/**
 * @Author 汤舒青
 * @Version 1.0
 * 模拟线程死锁
 */


public class DeadLock_ {
    public static void main(String[] args) {
        DeadLockDemo A = new DeadLockDemo(true);
        DeadLockDemo B = new DeadLockDemo(false);
        A.start();
        B.start();

    }
}

class DeadLockDemo extends Thread {
    static Object o1 = new Object();
    static Object o2 = new Object();
    boolean flag;

    public DeadLockDemo(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        //1. 如果fLag为T，线程A就会先得到/持有01对象锁，然后尝试去获取02对象锁

        //2.如果线程A得不到o2对象锁，就会BLocked

       //3. 如果flag为F，线程B就会先得到/持有o2对象锁，然后尝试去获取o1对象锁

     //4. 如果线程B得不到o1对象锁，就会BLocked
        if (flag) {
            synchronized (o1) {
                System.out.println(Thread.currentThread().getName() + "进入1");

                synchronized (o2) {
                    System.out.println(Thread.currentThread().getName() + "进入2");
                }
            }
        } else {
            synchronized (o2) {
                System.out.println(Thread.currentThread().getName() + "进入3");
                synchronized (o1) {
                    System.out.println(Thread.currentThread().getName() + "进入4");
                }
            }
        }
    }
}